package com.ynet.middleground.mobile.approve.exception;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.ynet.core.exception.BusinessException;
import com.ynet.middleground.mobile.approve.commom.ResponseResult;

/**
 * 项目名：ifp-mobile-approve <br>
 * 包名：com.ynet.middleground.mobile.approve.exception <br>
 * 类名：GlobalExceptionHandler <br>
 * 描述：
 *
 * @author Suremotoo
 * @create 2021-03-25 15:16
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public ResponseResult<Object> customExceptionHandler(BusinessException e) {
        return new ResponseResult<>(e.getCode(), e.getMessage());
    }

    /**
     * 对方法参数校验异常处理方法
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult<Map<String, Object>> handlerNotValidException(MethodArgumentNotValidException exception) {
        BindingResult result = exception.getBindingResult();
        Map<String, Object> maps;

        if (result.hasErrors()) {
            List<FieldError> fieldErrors = result.getFieldErrors();
            maps = new HashMap<>(fieldErrors.size());
            fieldErrors.forEach(error -> {
                maps.put(error.getField(), error.getDefaultMessage());
            });
        } else {
            maps = Collections.EMPTY_MAP;
        }
        return new ResponseResult<>("ECMA00001", maps.toString());
    }

}